package com.imooc.jdbc.smaple;

import com.imooc.jdbc.common.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TransactionSample {

    public static void main(String[] args) {


        Connection conn = null;
        PreparedStatement preStmt = null;


        try {
            conn = DbUtils.getConnection();
            conn.setAutoCommit(false);
            String insertSql = "INSERT INTO employee (dep_name,emp_name,salary) VALUES (?,?,?)";
            preStmt = conn.prepareStatement(insertSql);

            for(int i=1000; i< 2000; i++){
                preStmt.setString(1, "研发部");
                preStmt.setString(2, "员工" + i);
                preStmt.setFloat(3, 3500);

                preStmt.executeUpdate();
            }

            conn.commit();
            System.out.println("员工批量导入成功");
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                if (conn !=null && !conn.isClosed()) {
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeConnection(null, preStmt, conn);
        }

    }
}
